package io.shdxhl.simplerpc.server.zk;

import io.shdxhl.simplerpc.code.annotation.SimpleServer;
import io.shdxhl.simplerpc.code.bean.SimpleBeanFactory;
import io.shdxhl.simplerpc.code.config.SimpleConfiguration;
import io.shdxhl.simplerpc.code.registry.SimpleRegistry;
import io.shdxhl.simplerpc.code.utils.IPUtil;
import io.shdxhl.simplerpc.code.zk.ZkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Objects;

@Component
@DependsOn(value = "simpleBeanFactory")
@Slf4j
public class ZkRegistry implements SimpleRegistry {

    @Autowired
    private ZkUtil zkUtil;

    @Autowired
    private SimpleConfiguration simpleConfiguration;

    /**
     * 当前服务端节点注册到ZK
     */
    @Override
    public void serviceRegistry() {
        Map<String, Object> beansWithAnnotation = SimpleBeanFactory.getBeansWithAnnotation(SimpleServer.class);
        if(Objects.nonNull(beansWithAnnotation) && beansWithAnnotation.size() > 0) {
            for(Object bean : beansWithAnnotation.values()) {
                //先创建根节点
                zkUtil.createZkRootNode();
                //获取当前请求的IP
                String ip = IPUtil.getRealIp();
                SimpleServer simpleServer = bean.getClass().getAnnotation(SimpleServer.class);
                //获取当前注解的class type
                if(Objects.nonNull(simpleServer)) {
                    Class<?> clazz = simpleServer.type();
                    String serviceName = clazz.getSimpleName();//接口名称
                    //创建 代表接口的子节点
                    zkUtil.createZkPersistentNode(serviceName);
                    //在接口节点下创建代表提供者的临时节点
                    String providerNode = ip + ":" + simpleConfiguration.getPort();
                    zkUtil.createZKNode(serviceName + "/" + providerNode);
                    log.info("服务{}--{}完成注册", serviceName, providerNode);
                }
            }
        }

    }
}
